#!/bin/bash

# Flutter Rust Bridge 代码生成脚本

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

echo "🔧 Generating Flutter Rust Bridge bindings..."

# 检查 flutter_rust_bridge_codegen 是否安装
if ! command -v flutter_rust_bridge_codegen &> /dev/null; then
    echo "❌ flutter_rust_bridge_codegen not found. Installing..."
    cargo install flutter_rust_bridge_codegen
fi

# 创建输出目录
mkdir -p ../lib/generated
mkdir -p ../ios/Runner
mkdir -p ../macos/Runner
mkdir -p ../android/app/src/main/jni

# 生成绑定代码
# 注意：dart-output 必须指向一个目录，不能是文件
# 生成的代码会在该目录下创建 frb_generated.dart 等文件
flutter_rust_bridge_codegen generate \
    --rust-input crate::api \
    --dart-output ../lib/generated \
    --dart-entrypoint-class-name VioletMobileRust \
    --rust-root . \
    --rust-output src/frb_generated.rs \
    --no-dart-format \
    || {
        echo "❌ Failed to generate bindings. Trying with config file..."
        # 如果上面的命令失败，尝试使用配置文件
        flutter_rust_bridge_codegen generate \
            --config-file flutter_rust_bridge.yaml \
            || {
                echo "❌ Alternative method also failed."
                echo "Please check the configuration and ensure all dependencies are installed."
                exit 1
            }
    }

echo "✅ Bindings generated successfully!"
echo "📁 Dart output: ../lib/generated/frb_generated.dart"
echo "📁 Rust output: src/frb_generated.rs"
echo ""
echo "下一步："
echo "1. 检查生成的代码是否正确"
echo "2. 运行 'cargo build --release' 构建 Rust 库"
echo "3. 在 Flutter 中运行 'flutter pub get' 和 'flutter run'"

